/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.web.orm;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jfast.framework.exception.DataSourceException;
import com.jfast.framework.kit.StrKit;
import com.jfast.framework.util.ClassFactory;
import com.jfast.framework.web.orm.annotation.Column;

public class ModelBuilder {

    private static final ModelBuilder modelBuilder = new ModelBuilder();              
	
	public static ModelBuilder me(){
		return modelBuilder;
	}
	
	private ModelBuilder() {
		
	}
	
	public void fillStatement(PreparedStatement preparedStatement,Object... paras) throws SQLException{
		for(int i=0;i<paras.length;i++){
			preparedStatement.setObject(i+1,paras[i]);
		}
	}
	
	public <T>  List<T> builderModelList(ResultSet resultSet,Class<T> cla) throws SQLException{
    	List<T> list = new ArrayList<T>();
		try {
			while (resultSet.next()) {
				T t = ClassFactory.crateBean(cla);
				Field[] fieldield = cla.getDeclaredFields();
				for (Field field : fieldield) {
					field.setAccessible(true);
					Column column = field.getAnnotation(Column.class);
					if(StrKit.isNotEmpoty(column) && StrKit.isNotEmpoty(column.name())){
						field.set(t, resultSet.getObject(column.name()));
					}else{
						field.set(t, resultSet.getObject(field.getName()));
					}
				}
				list.add(t);
			}
			return list;
		} catch (Exception e) {
			throw new DataSourceException(e);
		}
	}
}
